package com.faxsun.core.order.dao;

import java.util.List;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.broadleafcommerce.common.persistence.EntityConfiguration;
import org.broadleafcommerce.core.order.domain.Order;
import org.broadleafcommerce.core.order.domain.OrderAttribute;
import org.broadleafcommerce.core.order.domain.OrderAttributeImpl;
import org.springframework.stereotype.Repository;

@Repository("fsOrderAttributeDao")
public class OrderAttributeDaoImpl implements OrderAttributeDao {

	@PersistenceContext(unitName = "blPU")
	protected EntityManager em;

	@Resource(name = "blEntityConfiguration")
	protected EntityConfiguration entityConfiguration;

	@Override
	public OrderAttribute create() {
		return (OrderAttribute) entityConfiguration.createEntityInstance(OrderAttribute.class.getName());
	}

	@Override
	public OrderAttribute readAtttributeById(long orderId) {
		return em.find(OrderAttributeImpl.class, orderId);
	}

	@Override
	public OrderAttribute save(OrderAttribute orderAttribute) {
		return em.merge(orderAttribute);
	}

	@Override
	public void delete(OrderAttribute orderAttribute) {
		if (!em.contains(orderAttribute)) {
			orderAttribute = readAtttributeById(orderAttribute.getId());
		}
		em.remove(orderAttribute);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<OrderAttribute> readOrderAttributesForOrder(Order order) {
		Query query = em.createQuery(
				"SELECT orderAttribute FROM org.broadleafcommerce.core.order.domain.OrderAttribute orderAttribute"
				+ " WHERE orderAttribute.order = :order");
		query.setParameter("order", order);
		return query.getResultList();
	}

}
